<template>
  <view
    class="wj-radio neumorphism u-line-2"
    :class="[
      { 'neumorphism-checked': getCheckedFlag() },
      { 'is-disabled': disabled },
    ]"
    @click="handleChange"
  >
    <slot></slot>
    <template v-if="!$slots.default">{{ label }}</template>
  </view>
</template>
<script lang="ts" setup>
import { Ref, inject, computed, nextTick } from 'vue';
const emit = defineEmits(['change', 'update:value']);
const handleChange = () => {
  nextTick(() => {
    if (props.disabled) {
      return;
    }
    model.value = props.value;
    emit('change', model.value);
  });
};
const props = defineProps<{
  value?: string | number | undefined;
  label?: string | number;
  disabled?: boolean;
}>();
type RadioGroupModelValue = {
  type: 'radio' | 'multiple';
  radioGroupModelValue: Ref<string | number | string[] | number[]>;
  updateRadioGroupModelValue: Function;
};
const injectData: RadioGroupModelValue | undefined = inject(
  'radioGroupModelValue'
);
const {
  radioGroupModelValue,
  updateRadioGroupModelValue,
  type: radioType,
} = injectData || {};
const model = computed({
  get() {
    return radioGroupModelValue ? radioGroupModelValue.value : props.value;
  },
  set(val) {
    // if (radioGroupModelValue?.value) {
    emit('update:value', val);
    return updateRadioGroupModelValue!(val);
    // }
  },
});

const getCheckedFlag = () => {
  if (!model.value && !props.value) {
    return true;
  }
  if (radioType) {
    return radioType === 'radio'
      ? model.value === props.value
      : (model.value as (string | number | undefined)[] | undefined)?.includes(
          props.value
        );
  }
  return model.value === props.value;
};
</script>
<style lang="scss" scoped>
.wj-radio {
  margin: 10rpx;
  cursor: pointer;
  background: #f0f2f5;
  color: #999;
  width: auto;
  height: 60rpx;
  padding: 0 30rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 30rpx;
  border: 1px solid #f0f2f5;
}
.neumorphism-checked {
  color: $u-type-primary;
  border: 1px solid $u-type-primary;
}
.is-disabled {
  color: #999;
}
</style>
